<template>
    <div class="container">
        <div class="handle-box">
                <el-form ref="form" :model="searchform" class="flex">
                    <el-form-item label="所属地区：">
                        <el-input v-model="searchform.name" placeholder="请输入地区" class="handle-input mr10"  @input="mohu()"></el-input>
                    </el-form-item>
                    <el-form-item label="所属街道：">
                        <el-input v-model="searchform.streetname" placeholder="请输入街道" class="handle-input mr10"  @input="streetmohu()"></el-input>
                    </el-form-item>
                    <el-form-item label="社区：">
                        <el-input v-model="searchform.communitname" placeholder="请输入社区" class="handle-input mr10" @input="communitmohu()"></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="楼号：">
                        <el-input v-model="name" placeholder="请输入楼号" class="handle-input mr10"></el-input>
                    </el-form-item>
                    <el-form-item label="单元号：">
                        <el-input v-model="name" placeholder="请输入单元号" class="handle-input mr10"></el-input>
                    </el-form-item>
                    <el-form-item label="门牌号：">
                        <el-input v-model="name" placeholder="请输入门牌号" class="handle-input mr10"></el-input>
                    </el-form-item> -->
                    <!-- <el-form-item label="日期范围：">
                       <el-date-picker
                            v-model="value1"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item> -->
                    <el-form-item class="flex">
                        <el-button type="primary" icon="el-icon-search" @click="searchbtn(searchform)">搜索</el-button>
                        <!-- <el-button type="danger" icon="el-icon-circle-close">清空</el-button> -->
                        <el-button type="success" icon="el-icon-circle-plus-outline" @click="addlistdatadiglog()">新增</el-button>
                        <el-button type="primary" @click="exportToExcel()" style="background:#409EFF;border:1px solid #409EFF">导出列表</el-button>
                        <el-button style="padding:0;border:0">
                             <el-upload
                            action="/上传文件的接口"
                            :on-change="onChange"
                            :auto-upload="false"
                            :show-file-list="false"
                            accept=".xls, .xlsx"  class="upload">
                        <el-button type="warning" icon="el-icon-folder-add" style="width:97px;height:33px">导入列表</el-button>
                        <!-- <el-button type="warning" icon="el-icon-folder-add" style="width:97px;height:33px">导出列表</el-button> -->
                    </el-upload>
                        </el-button>
                    </el-form-item>
                    
                    
                </el-form>
            </div>
            <el-table
                :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
            >
                <el-table-column type="index" :index="indexMethod" label="ID"></el-table-column>
                <el-table-column prop="REGION_NAME" label="所属地区"></el-table-column>
                <el-table-column prop="STREET_NAME" label="所属街道"></el-table-column>
                <el-table-column prop="COMMUNITY_NAME" label="社区"></el-table-column>
                <el-table-column prop="ADDRESS" label="地址"></el-table-column>
                <el-table-column prop="CONTACTS" label="联系人"></el-table-column>
                <el-table-column prop="TELEPHONE" label="联系人电话"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button> |
                        <el-button
                            type="text"
                            @click="handleDelete(scope.$index, scope.row)" style="color:red"
                        >删除</el-button> |
                        <el-button
                            type="text"
                            @click="jump()" style="color:#2A47BD"
                        >积分管理</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :current-page="currentPage"  
                    :page-size="pageSize"
                    :total="tableData.length"
                    @size-change="handleSizeChange"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
               <!-- 编辑弹出框 -->
            <el-dialog v-dialogDrag title="编辑社区" :visible.sync="editVisible" width="50%">
                <el-form ref="editform" :model="editform" label-width="70px" class="display">
                   <el-form-item label="所属地区：" :label-width="labelwidth" class="wid50">
                        <el-select disabled v-model="editform.REGION_ID" placeholder="请选择" @change="changevalue">
                          <el-option v-for="item in options" :key='item.REGION_ID' :label="item.REGION_NAME" :value="item.REGION_ID" >
                          </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属街道：" :label-width="labelwidth" class="wid50">
                        <el-select disabled  v-model="editform.STREET_NAME" placeholder="请选择">
                          <el-option v-for="item in optionsstreet" :key='item.STREET_ID' :label="item.STREET_NAME" :value="item.STREET_ID">
                          </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="社区：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.COMMUNITY_NAME"></el-input>
                    </el-form-item>
                    <el-form-item label="地址：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.ADDRESS"></el-input>
                    </el-form-item>
                    <el-form-item label="经度：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.LONGITUDE"></el-input>
                    </el-form-item>
                    <el-form-item label="纬度：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.LATITUDE"></el-input>
                    </el-form-item>
                    <el-form-item label="联系人：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.CONTACTS"></el-input>
                    </el-form-item>
                    <el-form-item label="联系人电话：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.TELEPHONE"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 新增弹出框 -->
            <el-dialog v-dialogDrag title="新增社区" :visible.sync="addeditVisible" width="50%">
                <el-form ref="form" :model="addform" label-width="70px" class="display" :rules="rules">
                    <el-form-item label="所属地区：" :label-width="labelwidth" class="wid50" prop="REGION_ID">
                        <el-select v-model="addform.REGION_ID" placeholder="请选择" @change="changevalue">
                          <el-option v-for="item in options" :key='item.REGION_ID' :label="item.REGION_NAME" :value="item.REGION_ID" >
                          </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属街道：" :label-width="labelwidth" class="wid50" prop="STREET_ID">
                        <el-select v-model="addform.STREET_ID" placeholder="请选择">
                          <el-option v-for="item in optionsstreet" :key='item.STREET_ID' :label="item.STREET_NAME" :value="item.STREET_ID">
                          </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="社区：" :label-width="labelwidth" class="wid50" prop="COMMUNITY_NAME">
                        <el-input v-model="addform.COMMUNITY_NAME"></el-input>
                    </el-form-item>
                    <el-form-item label="地址：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="addform.ADDRESS"></el-input>
                    </el-form-item>
                    <el-form-item label="经度：" :label-width="labelwidth" class="wid50" prop="LONGITUDE">
                        <el-input v-model="addform.LONGITUDE"></el-input>
                    </el-form-item>
                    <el-form-item label="纬度：" :label-width="labelwidth" class="wid50" prop="LATITUDE">
                        <el-input v-model="addform.LATITUDE"></el-input>
                    </el-form-item>
                    <el-form-item label="联系人：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="addform.CONTACTS"></el-input>
                    </el-form-item>
                    <el-form-item label="联系人电话：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="addform.TELEPHONE"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addeditVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addsaveEdit(addform)">确 定</el-button>
                </span>
            </el-dialog>
        </div>
</template>
<script>
import '../../assets/css/common.css'

export default {
    data(){
        return{
              currentPage:1, //初始页
                pagesize:10,    //    每页的数据
                rules: {
                REGION_ID: [
                  { required: true, message: '请选择新增社区所属地区', trigger: 'blur' },
                ],
                STREET_ID: [
                  { required: true, message: '请选择新增社区所属街道', trigger: 'blur' },
                ],
                COMMUNITY_NAME: [
                  { required: true, message: '请输入新增社区的名称', trigger: 'blur' }
                ],
                LONGITUDE: [
                  { required: true, message: '请输入真实经纬度', trigger: 'blur' }
                ],
                LATITUDE: [
                  { required: true, message: '请输入真实经纬度', trigger: 'blur' }
                ]},
                userList: [],
                address:'',
                name:'',
                value1: '',
                labelswidth: '160px',
                labelwidth: '120px',
                addform:{},
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            addeditVisible:false,
            options: [],
            editform: '',
            optionsstreet:[],
            searchform : {
                name: '',
                streetname: '',
                communitname: ''
            }
        }
    },
    created() {
        this.getdata();
        this.getselect();
        // this.getstreetselect()
    },
    methods: {
        // 获取表格数据
        async getdata(){
            const { data } = await this.$axios.get(this.$url + '/GetCommunityListApi')
            console.log(data) 
            this.tableData = data.filter(item=>{
                item.CREATETIME = item.CREATETIME.replace('T',' ')
                return item
            })
        },
        // 获取行政区下拉列表
        async getselect(){
            const { data } = await this.$axios.get(this.$url + '/GetRegionListApi')
            console.log(data)
            this.options = data.filter(item => {
              return item
            })
        },
        // 获取街道下拉列表
        async changevalue(e){
            const { data } =await this.$axios.get(this.$url + '/sreetListsApi?id='+e);
            this.optionsstreet = data.filter(item => {
                console.log(item)
                return item 
            })

        },
        // 新增弹框确定
        addsaveEdit(addform){
            console.log(addform)
            this.$axios({
                // url: this.$url+'/AddStreetApi',
                url:'http://111.160.78.62:9943/GarbagePointsBDEApi/NewData/AddCommunityApi',
                method: 'post',
                data:{
                    COMMUNITY_NAME: this.addform.COMMUNITY_NAME,
                    REGION_ID: this.addform.REGION_ID,
                    STREET_ID: this.addform.STREET_ID,
                    ADDRESS: this.addform.ADDRESS,
                    CONTACTS: this.addform.CONTACTS,
                    LONGITUDE: this.addform.LONGITUDE,
                    LATITUDE: this.addform.LATITUDE,
                    TELEPHONE: this.addform.TELEPHONE
                }
            }).then((res)=>{
                console.log(res)
                if(res.data.IsSucess){
                    this.$message.success('新增成功');
                    this.getdata()
                }
            })
            this.addeditVisible =false
            this.addform = Object.assign({},undefined)
        },
        // 打开新增弹框
        addlistdatadiglog(){
            this.addeditVisible = true
        },
        // 导出功能
        exportToExcel(){
            require.ensure([],()=>{
              const {export_json_to_excel} = require('../../excel/export2Excel');
              const tHeader = ['所属地区','所属街道', '社区','地址','联系人','联系人电话'];
              const filterVal = ['REGION_NAME','STREET_NAME', 'COMMUNITY_NAME','ADDRESS','CONTACTS','TELEPHONE'];
              const list = this.tableData;
              const data = this.formatJson(filterVal, list);
              console.log(data)
              export_json_to_excel(tHeader, data, "社区信息列表");
            });
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]));
        },
        // 模糊查询
         mohu() {
            var newdate = [];
            if(this.searchform.name){
                if(this.searchform.name)
                 this.tableData.filter(item=>{
                     console.log(item)
                    if(item.REGION_NAME.indexOf(this.searchform.name) != -1){
                        newdate.push(item)
                    }
                })
            }else if (this.searchform.name == ''){
                this.getdata()
            }
            this.tableData = newdate
        },
        streetmohu(){
             var streetname = this.searchform.streetname;
             var newdate = [];
             if(streetname){
                if(streetname)
                 this.tableData.filter(item=>{
                    //  console.log(item)
                    if(item.STREET_NAME.indexOf(streetname) != -1){
                        newdate.push(item)
                    }
                })
            }else if (streetname == ''){
                this.getdata()
            }
            this.tableData = newdate
        },
        communitmohu(){
             var communitname = this.searchform.communitname;
             var newdate = [];
             if(communitname){
                if(communitname)
                 this.tableData.filter(item=>{
                    //  console.log(item)
                    if(item.COMMUNITY_NAME.indexOf(communitname) != -1){
                        newdate.push(item)
                    }
                })
            }else if (communitname == ''){
                this.getdata()
            }
            this.tableData = newdate
        },
        // 搜索按钮
        searchbtn(searchform){
            console.log(searchform)
            this.tableData = this.tableData.filter(item =>{
                console.log(item)
                if(item.REGION_NAME.search(searchform.name) != -1){
                    if(searchform.streetname != ''){
                       this.tableData = item.filter(items =>{
                        if(items.STREET_NAME.search(searchform.streetname) !=-1){
                                console.log(items)
                            }
                        }) 
                    }
                    
                    
                }
            })
        },
        jump(){
            this.$router.push('/communityintegral')
        },
        // 编辑操作
        handleEdit(index, row) {
            this.editform =Object.assign({},row)
            this.editVisible = true;
        },
        indexMethod(index) {
          return index + 1;
        },
        // 删除
        handleDelete(index, row) {
            console.log(index,row)
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(res=>{
                var aa = {
                    COMMUNITY_ID: row.COMMUNITY_ID,
                }
                this.$axios({
                url: 'http://111.160.78.62:9943/GarbagePointsBDEApi/NewData/DeleteCommunityApi',
                method:'post',
                data: aa
                }).then(res=>{
                    this.$message.success('删除成功')
                    this.getdata()
                })
                
            }) 
        },
        // 保存编辑
        saveEdit() {
            let studenteList=this.editform;
            console.log(studenteList)
            console.log({
                    COMMUNITY_ID: studenteList.COMMUNITY_ID,
                    COMMUNITY_NAME: studenteList.COMMUNITY_NAME,
                    REGION_ID: studenteList.REGION_ID,
                    STREET_ID: studenteList.STREET_ID,
                    ADDRESS: studenteList.ADDRESS,
                    lng: studenteList.LONGITUDE,
                    lat: studenteList.LATITUDE,
                    CONTACTS: studenteList.CONTACTS,
                    TELEPHONE: studenteList.TELEPHONE
                })
            this.$axios({
                url:'http://111.160.78.62:9943/GarbagePointsBDEApi/NewData/UpdateCommunityApi',
                //url: this.$url+'/UpdateCommunityApi',
                method: 'post',
                data:{
                    COMMUNITY_ID: studenteList.COMMUNITY_ID,
                    COMMUNITY_NAME: studenteList.COMMUNITY_NAME,
                    REGION_ID: studenteList.REGION_ID,
                    STREET_ID: studenteList.STREET_ID,
                    ADDRESS: studenteList.ADDRESS,
                    LONGITUDE: studenteList.LONGITUDE,
                    LATITUDE: studenteList.LATITUDE,
                    CONTACTS: studenteList.CONTACTS,
                    TELEPHONE: studenteList.TELEPHONE
                }
            }).then(item =>{
                if(item.data.IsSucess){
                    this.$message.success('编辑成功')
                    this.getdata()
                }
            })
            this.editVisible = false;
           
        },
              // 文件选择回调
   onChange(file, fileList) {
    //  console.log(fileList);
     this.fileData = file; // 保存当前选择文件
     this.readExcel(); // 调用读取数据的方法
   },
   // 读取数据
   readExcel(e) {
     let that = this;
     const files = that.fileData;
     console.log(files);
     if (!files) {
       //如果没有文件
       return false;
     } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
       this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
       return false;
     }
     const fileReader = new FileReader();
     console.log(fileReader)
     fileReader.onload = ev => {
       try {
         const data = ev.target.result;
        //  console.log(ev.target)
        //  console.log(this);
         const workbook = this.XLSX.read(data, {
           type: "binary"
         });
         if (workbook.SheetNames.length >= 1) {
        //    this.$message({
        //      message: "导入数据表格成功",
        //      showClose: true,
        //      type: "success"
        //    });
         }
         const wsname = workbook.SheetNames[0]; //取第一张表
         const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
        //  this.$axios({
        //   //  this.$url + '/ImportRubbishBoxApi'
        //    url:this.$url +'/ImportCommunityApi' ,
        //    method:'post',
        //    data: ws
        //  }).then(res=>{
        //      console.log(res)
        // //    if(res.data.IsSucess){
        // //        this.$message.success('导入成功')
        // //        this.getdata()
        // //    }
        //  })
         console.log(ws)
         that.outputs = []; //清空接收数据
        //  for (var i = 0; i < ws.length; i++) {
        //    var sheetData = {
        //      // 键名为绑定 el 表格的关键字，值则是 ws[i][对应表头名]
        //     //  ID: ws[i]["ID"],
        //      REGION_NAME: ws[i][""],
        //      STREET_NAME: ws[i]["STREET_NAME"],
        //      COMMUNITY_NAME: ws[i]['COMMUNITY_NAME'],
        //      ADDRESS: ws[i]["ADDRESS"],
        //      CONTACTS: ws[i]["CONTACTS"],
        //      TELEPHONE: ws[i]["TELEPHONE"],
        //     //  LOCATION: ws[i]["位置"],
        //     //  WEIGHT_YH: ws[i]['重量'],
        //     //  SIZE: ws[i]["类型"],
        //     //  PHOTO: ws[i]['图片'],
        //     //  REMARK: ws[i]['备注'],
        //    };
        //    that.tableData.unshift(sheetData);
        //  }
         
         let exceldata =  [] 
         ws.filter(item=>{
             var sheetData = {
              REGION_NAME: item["所属地区"],
              STREET_NAME: item["所属街道"],
              COMMUNITY_NAME: item['社区'],
              ADDRESS: item["地址"],
              CONTACTS: item["联系人"],
              TELEPHONE: item["联系人电话"],
           }
             console.log(sheetData);
             exceldata.push(sheetData)
         })
         console.log(exceldata)
        this.$axios({
          url: this.$url + '/ImportCommunityApi',
          method: 'post',
          data: exceldata
        }).then(res=>{
            console.log(res)
          if(res.data.IsSucess){
            this.$message.success('导入成功')
            this.getdata()
          }
        })
         this.$refs.upload.value = "";
       } catch (e) {
         return false;
       }
     };
     // 如果为原生 input 则应是 files[0]
     fileReader.readAsBinaryString(files.raw);
   },
        // 分页导航
        handlePageChange(currentPage) {
            this.currentPage = currentPage;
            console.log(this.currentPage)
            // this.$set(this.query, 'pageIndex', val);
            // this.getData();
        },
        handleSizeChange(size){
            this.pagesize = size;
            console.log(this.pagesize)
        },
       
    }
}
</script>
<style scoped>
.el-select{
    width: 100%;
}
/deep/.el-upload__input{
    display: none;
}
/deep/.el-form-item__content{
    display: flex;
}
</style>